/**
 * Copyright (C) 2015-2016 Guangzhou Xunhong Network Technology Co., Ltd. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jxccp.ui;

import android.os.Build;
import android.os.Handler;
import android.os.LocaleList;
import android.os.Looper;
import android.text.TextUtils;

import com.jxccp.im.chat.common.message.JXMessage;
import com.jxccp.im.chat.common.message.JXMessage.ChatType;
import com.jxccp.im.chat.common.message.JXMessageUtil;
import com.jxccp.im.chat.manager.JXImManager;
import com.jxccp.im.util.log.JXLog;
import com.jxccp.ui.entities.JXCommodity;
import com.jxccp.ui.entities.JXOrderInfo;
import com.jxccp.ui.entities.ZhuiyiLoanOrderEntity;
import com.jxccp.ui.entities.ZhuiyiProductOrderEntity;
import com.jxccp.ui.listeners.JXLinkClickListener;
import com.jxccp.ui.listeners.JXThirdPartyOrderListener;
import com.jxccp.ui.service.JXNotifyManager;
import com.jxccp.ui.utils.JXNotificationUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

/**
 * @Description: TODO
 * @date 2015-9-16 上午11:05:49
 */
public class JXUiHelper{

    public static final String JX_ATTR_TYPE = "jxui_attr_type";

    public static final String JX_ATTR_TYPE_CANCEL_WAIT = "jxui_attr_cancel_wait";

    /**
     * 非转接人工或机器人
     */
    public static final int TAG_NOT_TRANSFER = 0;

    /**
     * 转接到机器人服务
     */
    public static final int TAG_TRANSFER_ROBOT = 1;

    /**
     * 转接到人工服务
     */
    public static final int TAG_TRANSFER_CUSTOMER_SERVICE = 2;


    /**
     * 取消客服等待
     */
    public static final int TAG_CANCEL_WAIT = 3;

    /**
     * 提交满意度
     */
    public static final int TAG_EVALUTE = 4;

    /**
     * 获取快捷提问问题列表
     */
    public static final int TAG_QUICK_QUESTION = 5;

    /**
     * 取消客服等待
     */
    public static final int TAG_CLOSE_SESSION = 6;

    private static JXUiHelper demoHelper;

    private String PlayingMsgID;

    private boolean hasRobot = false;

    // 超时评价消息缓存
    private Map<String, JXMessage> enableEvaluateCache;

    private String robotNickname = null;

    private Handler handler = new Handler(Looper.getMainLooper());

    private JXCommodity jxCommodity;

    private boolean isChatPage = false;

    /**
     * 消息盒子未读消息数
     */
    private int messageBoxUnreadCount = 0;

    /**
     * 推送token
     */
    private String pushDevicesToken = "test_token";

    /**
     * 组织id
     */
    private String suborgId = null;

    /**
     * 可反馈机器人消息
     */
    private HashSet<String> enableRobotFeedBackMsgSet;
    /**
     * 已反馈机器人消息
     */
    private Set<String> robotFeedBackedMsgSet;

    /**
     * 机器人反馈感谢语
     */
    private String robotFeedBackThanksMsg;

    /**
     * 转人工提示语缓存
     */
    private Set<String> transferTipsMsg;

    /**
     * 当前渠道号
     */
    private String currentChannelNo;

    /**
     * 上一个渠道号
     */
    private String lastChannelNo;

    /**
     * 是否允许发图片给机器人
     */
    private boolean sendImgToRobotEnable = false;

    /**
     * 是否允许发语音给机器人
     */
    private boolean sendVoiceToRobotEnable = false;

    /**
     * 切换渠道后是否重新请求
     */
    private boolean reRequestAfterChangeChannel = false;

    /**
     * 机器人输入联想开关
     */
    private boolean robotInputAssociateEnable = false;

    /**
     * 链接点击监听器
     */
    private JXLinkClickListener linkClickListener;

    /**
     * 是否启用留言箱
     */
    private boolean msgBoxEnable = true;

    /**
     * 是否启用手动转人工按钮
     */
    private boolean showRobotTransferEnable = true;

    /**
     * 是否启用关闭会话按钮
     */
    private boolean showEndSessionEnable = true;

    /**
     * 第三方订单监听器
     */
    private JXThirdPartyOrderListener thirdPartyOrderListener;

    /**
     * 第三方订单默认分页大小
     */
    private int thirdPartyOrderDefaultPageSize = 15;

    /**
     * 是否消息列表页面
     */
    private boolean isConversationPage = false;

    /**
     * 是否通知会话结束消息
     */
    private boolean isNotifyEndMsg = true;

    /**
     * 启用常用问题，目前默认暂不开启，常用问题仅在灰度上线
     */
    private boolean useCommonQuestion =true;

    /**
     * 自助下单地址
     */
    private String selfServiceOrderUrl ;

    /**
     *  机器人是否区分头像
     */
    private boolean enbaleRobotHeadImage = true;

    /**
     * url scheme配置
     */
    private List<String> schemeList = new ArrayList<String>();

    /**
     * 排队提示语
     */
    private String ququeMsg;

    /**
     * 会话请求码
     */
    public static final int JX_CONVERSATION_REQUEST_CODE = 101;
    /**
     * 会话返回码
     */
    public static final int  JX_CONVERSATION_RESULT_CODE= 200;

    private JXUiHelper() {
        enableEvaluateCache = new HashMap<String, JXMessage>();
        enableRobotFeedBackMsgSet = new HashSet<>();
        robotFeedBackedMsgSet = new HashSet<>();
    }

    public static JXUiHelper getInstance() {
        if (null == demoHelper) {
            synchronized (JXUiHelper.class) {
                if (null == demoHelper) {
                    demoHelper = new JXUiHelper();
                }
            }
        }
        return demoHelper;
    }

    public String getPlayingMsgID() {
        return PlayingMsgID;
    }

    public void setPlayingMsgID(String playingMsgID) {
        PlayingMsgID = playingMsgID;
    }

    // public static String mcsID = null;

    private OnConversationListener conversationListener;

    public void setConversationListListener(OnConversationListener conversationListener) {
        this.conversationListener = conversationListener;
    }

    /**
     * @Description: 通知会话窗口更新
     * @date 2015-9-16 上午11:24:39
     */
    public void notifyConversationListChange() {
        handler.post(new Runnable() {

            @Override
            public void run() {
                if (conversationListener != null) {
                    conversationListener.onConversationChanged();
                }
            }
        });
    }

    public interface OnConversationListener {
        public void onConversationChanged();
    }

    public JXMessage saveSessionMsg(String tipsMessage, String skillsId, Map<String, Object> map) {
        return JXMessageUtil.saveNotification(skillsId, ChatType.CUSTOMER_SERVICE, tipsMessage,
                false, map);
    }

    public static final int INVALID_INT = -1;

    private int mTitleHeight = INVALID_INT;

    private int chatBgdrawableResId = INVALID_INT;

    private int inputMenuHeight = INVALID_INT;

    private int functionPanelHeight = INVALID_INT;

    private int expressionPanelHeight = INVALID_INT;

    private int mTitleBgColorId = INVALID_INT;

    private int mTitleLeftBgResId = INVALID_INT;

    private String mConversationExitTips = null;

    private int mTitleTextColorResId = INVALID_INT;

    private int mNoificationIcon = INVALID_INT;

    private int mMsgBoxResId = INVALID_INT;

    private int mTransferIconResId = INVALID_INT;

    private int mEndSessionIconResId = INVALID_INT;

    public int getmTitleHeight() {
        return mTitleHeight;
    }

    /**
     * 设置标题栏高度
     *
     * @param mTitleHeight
     */
    public void setmTitleHeight(int mTitleHeight) {
        this.mTitleHeight = mTitleHeight;
    }

    public int getChatBgdrawableResId() {
        return chatBgdrawableResId;
    }

    /**
     * 设置聊天背景
     *
     * @param chatBgdrawableResId
     */
    public void setChatBgdrawableResId(int chatBgdrawableResId) {
        this.chatBgdrawableResId = chatBgdrawableResId;
    }

    public int getInputMenuHeight() {
        return inputMenuHeight;
    }

    /**
     * 设置输入布局的高度
     *
     * @param inputMenuHeight
     */
    public void setInputMenuHeight(int inputMenuHeight) {
        this.inputMenuHeight = inputMenuHeight;
    }

    public int getFunctionPanelHeight() {
        return functionPanelHeight;
    }

    /**
     * 设置功能面板高度
     *
     * @param functionPanelHeight
     */
    public void setFunctionPanelHeight(int functionPanelHeight) {
        this.functionPanelHeight = functionPanelHeight;
    }

    public int getExpressionPanelHeight() {
        return expressionPanelHeight;
    }

    /**
     * 设置表情面板高度
     *
     * @param expressionPanelHeight
     */
    public void setExpressionPanelHeight(int expressionPanelHeight) {
        this.expressionPanelHeight = expressionPanelHeight;
    }

    /**
     * 设置标题栏颜色
     *
     * @return
     */
    public void setmTitleBgColorId(int mTitleBgColorId) {
        this.mTitleBgColorId = mTitleBgColorId;
    }

    public int getmTitleBgColorId() {
        return mTitleBgColorId;
    }

    /**
     * 设置标题栏左侧图标
     **/
    public void setmTitleLeftImgResId(int mTitleLeftResId) {
        this.mTitleLeftBgResId = mTitleLeftResId;
    }

    public int getmTitleLeftImgResId() {
        return mTitleLeftBgResId;
    }

    public String getmConversationExitTips() {
        return mConversationExitTips;
    }

    /**
     * 设置会话被结束时显示提示
     *
     * @param mConversationExitTips
     */
    public void setmConversationExitTips(String mConversationExitTips) {
        this.mConversationExitTips = mConversationExitTips;
    }

    private int currentPosition = -1;

    public int getCurrentPosition() {
        return currentPosition;
    }

    public void setCurrentPosition(int currentPosition) {
        this.currentPosition = currentPosition;
    }

    public int getmTitleTextColorResId() {
        return mTitleTextColorResId;
    }

    /**
     * 设置标题栏的文字颜色
     *
     * @param mTitleTextColorResId
     */
    public void setmTitleTextColorResId(int mTitleTextColorResId) {
        this.mTitleTextColorResId = mTitleTextColorResId;
    }

    public int getmNoificationIcon() {
        return mNoificationIcon;
    }

    /**
     * 设置通知图标
     * @return
     */
    public void setmNoificationIcon(int mNoificationIcon) {
        this.mNoificationIcon = mNoificationIcon;
    }

    /**
     * 设置消息箱图标
     * @return
     */
    public int getmMsgBoxResId() {
        return mMsgBoxResId;
    }

    public void setmMsgBoxResId(int mMsgBoxResId) {
        this.mMsgBoxResId = mMsgBoxResId;
    }

    public int getmTransferIconResId() {
        return mTransferIconResId;
    }

    public void setmTransferIconResId(int mTransferIconResId) {
        this.mTransferIconResId = mTransferIconResId;
    }

    public int getmEndSessionIconResId() {
        return mEndSessionIconResId;
    }

    public void setmEndSessionIconResId(int mEndSessionIconResId) {
        this.mEndSessionIconResId = mEndSessionIconResId;
    }

    public void saveEnableEvaluateMessage(final JXMessage message) {
        enableEvaluateCache.put(message.getMessageId(), message);
        // 暂时不做有评价消息的时效控制
        // evaTimeOutHandler.postDelayed(new Runnable() {
        // public void run() {
        // enableEvaluateCache.remove(message.getMessageId());
        // JXImManager.McsUser.getInstance().saveMcsEndMessage();
        // notifySendMessageSuccess(message);
        // }
        // }, 600*1000);
    }

    public boolean isEnableEvaluateMessage(JXMessage message) {
        if (enableEvaluateCache.containsKey(message.getMessageId())) {
            return true;
        }
        return false;
    }

    public boolean isHasRobot() {
        return hasRobot;
    }

    public void setHasRobot(boolean hasRobot) {
        this.hasRobot = hasRobot;
    }

    public void destroy() {
        JXNotificationUtils.cancelAllNotifty();
        enableEvaluateCache = null;
        enableRobotFeedBackMsgSet = null;
        robotFeedBackedMsgSet = null;
        JXNotifyManager.getInstance().removeLintner();
    }

    public int getMessageBoxUnreadCount() {
        return messageBoxUnreadCount;
    }

    public void setMessageBoxUnreadCount(int messageBoxUnreadCount) {
        synchronized (JXUiHelper.class) {
            this.messageBoxUnreadCount = messageBoxUnreadCount;
        }
    }

    public String getRobotNickname() {
        return robotNickname;
    }

    public void setRobotNickname(String robotNickname) {
        this.robotNickname = robotNickname;
    }

    public JXCommodity getJxCommodity() {
        return jxCommodity;
    }

    public void setJxCommodity(JXCommodity jxCommodity) {
        this.jxCommodity = jxCommodity;
    }

    /**
     * 消息盒子更新回调
     */
    public interface MessageBoxListener {
        /**
         * 消息盒子更新
         */
        public void onUpdate();
    }

    private List<MessageBoxListener> messageBoxListeners = new ArrayList<>();

    public void addMessageBoxListener(MessageBoxListener listener) {
        synchronized (messageBoxListeners) {
            if (listener != null) {
                if (!messageBoxListeners.contains(listener)) {
                    messageBoxListeners.add(listener);
                }
            }
        }
    }

    public void removeMessageBoxListener(MessageBoxListener listener) {
        synchronized (messageBoxListeners) {
            if (listener != null) {
                messageBoxListeners.remove(listener);
            }
        }
    }

    /**
     * 通知ui进行更新
     */
    public void notifyMessageBoxUpdate() {
        for (MessageBoxListener listener : messageBoxListeners) {
            listener.onUpdate();
        }
    }

    /**
     * 快捷提问更新回调
     */
    public interface QuickQuestionsListener {
        public void onUpdate();
    }

    private QuickQuestionsListener quickQuestionsListener;

    public void addQuickQuestionsListener(QuickQuestionsListener listener) {
        if (listener != null) {
            quickQuestionsListener = listener;
        }
    }

    public void removeQuickQuestionsListener() {
        quickQuestionsListener = null;
    }

    /**
     * 通知ui进行更新
     */
    public void notifyQuickQuestionsUpdate() {
        if (quickQuestionsListener != null) {
            quickQuestionsListener.onUpdate();
        }
    }

    public boolean isChatPage() {
        return isChatPage;
    }

    public void setChatPage(boolean chatPage) {
        isChatPage = chatPage;
    }

    public String getPushDevicesToken() {
        return pushDevicesToken;
    }

    public void setPushDevicesToken(String pushDevicesToken) {
        this.pushDevicesToken = pushDevicesToken;
    }

    public String getSuborgId() {
        return suborgId;
    }

    public void setSuborgId(String suborgId) {
        this.suborgId = suborgId;
    }

    private Locale locale = null;

    public static final String DEFAULT_COUNTRY = Locale.getDefault().getCountry();
    public static final String DEFAULT_LANGUAGE = Locale.getDefault().getLanguage();
    public static Locale SYSTEM_LOCALE = new Locale(DEFAULT_LANGUAGE, DEFAULT_COUNTRY);

    public void setLanguage(Locale locale) {
        JXLog.d("set locate =" + locale.toString());
        this.locale = locale;
        JXImManager.Config.getInstance().setLanguage(locale);
    }

    public Locale getLanguge() {
        if (locale == null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                LocaleList localeList = LocaleList.getDefault();
                locale = localeList.get(0);
                SYSTEM_LOCALE = localeList.get(0);
                JXLog.d("default locate =" + LocaleList.getDefault().get(0));
            } else {
                locale = Locale.getDefault();
                SYSTEM_LOCALE = Locale.getDefault();
            }
        }
        JXLog.d("get locate =" + locale.toString());
        return this.locale;
    }

    public HashSet<String> getEnableRobotFeedBackMsgSet() {
        if (enableRobotFeedBackMsgSet == null){
            enableRobotFeedBackMsgSet = new HashSet<>();
        }
        return enableRobotFeedBackMsgSet;
    }

    public void addEnableRobotFeedBackMsgSet(String msgId) {
        if (enableRobotFeedBackMsgSet == null){
            enableRobotFeedBackMsgSet = new HashSet<>();
        }
        this.enableRobotFeedBackMsgSet.add(msgId);
    }

    public Set<String> getRobotFeedBackedMsgSet() {
        if (robotFeedBackedMsgSet == null){
            robotFeedBackedMsgSet = new HashSet<>();
        }
        return robotFeedBackedMsgSet;
    }

    public void addRobotFeedBackedMsgSet(String msgId) {
        if (robotFeedBackedMsgSet == null){
            robotFeedBackedMsgSet = new HashSet<>();
        }
        this.robotFeedBackedMsgSet.add(msgId);
    }

    public String getRobotFeedBackThanksMsg() {
        return robotFeedBackThanksMsg;
    }

    public void setRobotFeedBackThanksMsg(String robotFeedBackThanksMsg) {
        this.robotFeedBackThanksMsg = robotFeedBackThanksMsg;
    }

    public Set<String> getTransferTipsMsgSet() {
        if (transferTipsMsg == null){
            transferTipsMsg = new HashSet<>();
        }
        return transferTipsMsg;
    }

    public void addTransferTipsMsgSet(String msgId) {
        if (transferTipsMsg == null){
            transferTipsMsg = new HashSet<>();
        }
        this.transferTipsMsg.add(msgId);
    }

    public void setCurrentChannelNo(String currentChannelNo) {
        this.lastChannelNo = this.currentChannelNo;
        this.currentChannelNo = currentChannelNo;
    }

    public boolean isSameChannelNo(String channelNo){
        if (channelNo != null && channelNo.equals(lastChannelNo)){
            return true;
        }else {
            return  false;
        }
    }

    public boolean sendImgToRobotEnable() {
        return sendImgToRobotEnable;
    }

    public void setSendImgToRobotEnable(boolean sendImgToRobotEnable) {
        this.sendImgToRobotEnable = sendImgToRobotEnable;
    }

    public boolean reRequestAfterChangeChannelEnable() {
        return reRequestAfterChangeChannel;
    }

    public void setReRequestAfterChangeChannel(boolean reRequestAfterChangeChannel) {
        this.reRequestAfterChangeChannel = reRequestAfterChangeChannel;
    }

    public boolean robotInputAssociateEnable() {
        return robotInputAssociateEnable;
    }

    public void setRobotInputAssociateEnable(boolean robotInputAssociateEnable) {
        this.robotInputAssociateEnable = robotInputAssociateEnable;
    }

    public JXLinkClickListener getLinkClickListener() {
        return linkClickListener;
    }

    public void addLinkClickListener(JXLinkClickListener linkClickListener) {
        if (linkClickListener != null){
            this.linkClickListener = linkClickListener;
        }
    }

    public void removeLinkClickListener(){
        linkClickListener = null;
    }

    public boolean msgBoxEnable() {
        return msgBoxEnable;
    }

    public void setMsgBoxEnable(boolean msgBoxEnable) {
        this.msgBoxEnable = msgBoxEnable;
    }

    public boolean isShowRobotTransferIcon() {
        return showRobotTransferEnable;
    }

    public void setShowRobotTransferEnable(boolean showRobotTransferEnable) {
        this.showRobotTransferEnable = showRobotTransferEnable;
    }

    public boolean isShowEndSessionIcon() {
        return showEndSessionEnable;
    }

    public void setShowEndSessionEnable(boolean showEndSessionEnable) {
        this.showEndSessionEnable = showEndSessionEnable;
    }

    public void addThirdPartyOrderListener(JXThirdPartyOrderListener listener) {
        if (listener != null) {
            thirdPartyOrderListener = listener;
        }
    }

    public void removeThirdPartyOrderListener() {
        thirdPartyOrderListener = null;
    }

    public List<JXOrderInfo> fetchThirdPartyOrderList(int startIndex , int PageSize){
        if (thirdPartyOrderListener != null){
            return  thirdPartyOrderListener.fetchOrderlist(startIndex,PageSize);
        }
        return  null;
    }

    public List<ZhuiyiProductOrderEntity> fetchZhuiyiProductOrderList(int startIndex , int PageSize){
        if (thirdPartyOrderListener != null){
            return  thirdPartyOrderListener.fetchZhuiyiProductOrderlist(startIndex,PageSize);
        }
        return  null;
    }

    public List<ZhuiyiLoanOrderEntity> fetchZhuiyiLoanOrderList(int startIndex , int PageSize){
        if (thirdPartyOrderListener != null){
            return  thirdPartyOrderListener.fetchZhuiyiLoanOrderlist(startIndex,PageSize);
        }
        return  null;
    }

    public int getThirdPartyOrderDefaultPageSize() {
        return thirdPartyOrderDefaultPageSize;
    }

    public void setThirdPartyOrderDefaultPageSize(int thirdPartyOrderDefaultPageSize) {
        this.thirdPartyOrderDefaultPageSize = thirdPartyOrderDefaultPageSize;
    }

    public boolean sendVoiceToRobotEnable() {
        return sendVoiceToRobotEnable;
    }

    public void setSendVoiceToRobotEnable(boolean sendVoiceToRobotEnable) {
        this.sendVoiceToRobotEnable = sendVoiceToRobotEnable;
    }


    public boolean isConversationPage() {
        return isConversationPage;
    }

    public void setConversationPage(boolean conversationPage) {
        isConversationPage = conversationPage;
    }

    public boolean isNotifyEndMsg() {
        return isNotifyEndMsg;
    }

    public void setNotifyEndMsg(boolean notifyEndMsg) {
        isNotifyEndMsg = notifyEndMsg;
    }

    public boolean isUseCommonQuestion() {
        return useCommonQuestion;
    }

    public void setUseCommonQuestion(boolean useCommonQuestion) {
        this.useCommonQuestion = useCommonQuestion;
    }

    public String getSelfServiceOrderUrl() {
        if (TextUtils.isEmpty(selfServiceOrderUrl)){
            return "http://web.jiaxintest.com:9000/createOrder.html";
        }
        return selfServiceOrderUrl;
    }

    public void setSelfServiceOrderUrl(String selfServiceOrderUrl) {
        this.selfServiceOrderUrl = selfServiceOrderUrl;
    }

    public boolean isEnbaleRobotHeadImage() {
        return enbaleRobotHeadImage;
    }

    public void setEnbaleRobotHeadImage(boolean enbaleRobotHeadImage) {
        this.enbaleRobotHeadImage = enbaleRobotHeadImage;
    }

    public void addScheme(String scheme){
        schemeList.add(scheme);
    }

    public List<String> getSchemeList() {
        return schemeList;
    }

    public void setSchemeList(List<String> schemeList) {
        this.schemeList = schemeList;
    }
    public String getQuqueMsg() {
        return ququeMsg;
    }

    public void setQuqueMsg(String ququeMsg) {
        this.ququeMsg = ququeMsg;
    }
}
